package com.toprs.base.exception

import com.toprs.base.annotation.Slf4j2
import com.toprs.base.annotation.Slf4j2.Companion.log
import com.toprs.base.config.RequestHolder
import com.toprs.base.entity.Log
import com.toprs.base.mapper.LogMapper
import com.toprs.base.mapper.insert
import com.toprs.base.result.Result
import jakarta.servlet.http.HttpServletRequest
import org.postgresql.util.PSQLException
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice


@Slf4j2
@RestControllerAdvice
class ExceptionHandler(val logMapper: LogMapper) {


    private fun insertErrorLog(request: HttpServletRequest, message: String) {

        log.error("调用接口 `${request.requestURI} 出错：${message}")
        val login = Log()
        login.logContent = "调用接口${request.requestURI} 出错：${message}"
        login.username = RequestHolder.getUsername()
        login.logType = 3
        login.ip = request.remoteAddr
        logMapper.insert(login)
    }


    @ExceptionHandler(CustomException::class)
    fun handleCustomException(request: HttpServletRequest, exception: CustomException): Result<String> {
        insertErrorLog(request, exception.message.toString())
        return Result.error(exception.message.toString())
    }


    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleArgException(request: HttpServletRequest, exception: MethodArgumentNotValidException): Result<String> {
        val message = exception.bindingResult.allErrors[0].defaultMessage.toString()
        insertErrorLog(request, message)
        return Result.error(message)
    }

    @ExceptionHandler(PSQLException::class)
    fun handlePSQLException(request: HttpServletRequest, exception: PSQLException): Result<String> {
        val message = exception.message!!
        insertErrorLog(request, message)
        return Result.error("数据库查询错误")
    }

    @ExceptionHandler(HttpMessageNotReadableException::class)
    fun handleHttpMessageNotReadableException(request: HttpServletRequest, exception: HttpMessageNotReadableException): Result<String> {
        val message = exception.message!!
        insertErrorLog(request, message)
        return Result.error("参数错误！")
    }


}